package com.itheima.controller;

import com.itheima.common.R;
import com.itheima.pojo.Employee;
import com.itheima.pojo.Page;
import com.itheima.service.EmployeeService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author wuyiqiang
 * @2022/6/13 19:57
 */
@RestController
@RequestMapping(value="/employee",produces = "application/json;charset=utf-8")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 员工登录
     *
     * @param employee
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public R<Employee> login(@RequestBody Employee employee) {
        //md5加密密码
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        employee.setPassword(password);

        Employee login = employeeService.login(employee);
        if (login == null) {
            return R.error("用户名或者密码错误，请重新输入");
        }
        if (login.getStatus() == 0) {
            R.error("用户被禁用，请联系管理员");
        }

        //设置token
        String s = System.currentTimeMillis() + login.getId();
        String token = DigestUtils.md5DigestAsHex(s.getBytes());
        login.setToken(token);

        //传token进redis
        redisTemplate.opsForValue().set(token, employee.getUsername(), 10, TimeUnit.DAYS);
        return R.success(login);
    }

    /**
     * 登出
     *
     * @param request
     */
    @PostMapping("/logout")
    public R logout(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null) {
            redisTemplate.delete(token);
            return R.success("退出成功");
        }
        return R.error("退出失败");
    }


    /**
     * 分页查询
     *
     * @param name
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(@Param("name") String name, @Param("page") Integer page, @Param("pageSize") Integer pageSize) {
        return employeeService.page(name, page, pageSize);
    }

    /**
     * 根据id查询员工
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R selectById(@PathVariable String id) {
        Employee employee = employeeService.updateById(id);
        return R.success(employee);
    }

    /**
     * 新增用户
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    public R save(HttpServletRequest request, @RequestBody Employee employee) {
        //设置默认密码为123456，并进行md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //设置id
        String userId = System.currentTimeMillis() + "";
        employee.setId(userId);
        //设置默认状态
        employee.setStatus(1);
        //获取当前时间并写入
        SimpleDateFormat sdf = new SimpleDateFormat();
        sdf.applyPattern("yyyy-MM-dd HH:mm:ss a");
        Date date = new Date();
        //设置创建时间
        employee.setCreateTime(date);
        //设置更新时间
        employee.setUpdateTime(date);
        //设置创建人和修改人的id
        String username = tokenToUsername(request);
        employee.setCreateUser(username);
        employee.setUpdateUser(username);

        try {
            int save = employeeService.add(employee);
            if (save > 0) {
                return R.success(save);
            }
        } catch (Exception e) {
            System.out.println("员工重复添加==============debug");
        }

        return R.error(employee.getUsername() + "已存在");
    }

    /**
     * 修改员工
     *
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    @ResponseBody
    public R update(HttpServletRequest request, @RequestBody Employee employee) {
        String username = tokenToUsername(request);
        System.out.println(username+"===========debug");
        employee.setUpdateUser(username);
        //获取当前时间并写入
        SimpleDateFormat sdf = new SimpleDateFormat();
        sdf.applyPattern("yyyy-MM-dd HH:mm:ss a");
        Date date = new Date();
        employee.setUpdateTime(date);

        employeeService.update(employee);
        return R.success("员工信息修改成功");

    }

    /**
     * 利用token获得当前页面用户名
     *
     * @param request
     * @return
     */
    public String tokenToUsername(HttpServletRequest request) {
        //用户id设置
        String token = request.getHeader("Authorization");

        String username = (String) redisTemplate.opsForValue().get(token);

        return username;
    }
}
